package com.syq.service.impl;

import com.syq.bean.Menu;
import com.syq.bean.Role;
import com.syq.dao.MiddleDao;
import com.syq.dao.RoleDao;
import com.syq.dao.impl.MiddleDaoImpl;
import com.syq.dao.impl.RoleDaoImpl;
import com.syq.service.RoleService;

import java.util.ArrayList;
import java.util.List;

public class RoleServiceImpl implements RoleService {
    private RoleDao roleDao = new RoleDaoImpl();
    private MiddleDao middleDao = new MiddleDaoImpl();
    @Override
    public List<Role> getList() {
        return roleDao.getList();
    }

    @Override
    public List<Role> getRoleList(int pageIndex, int pageSize) {
        return roleDao.getRoleList(pageIndex,pageSize);
    }

    @Override
    public int total() {
        return roleDao.total();
    }

    @Override
    public int addRole(String roleName,String state,String[] ids) {
        int k1= 0;
        try {
            Role role = new Role();
            role.setRoleState(Integer.parseInt(state));
            role.setRoleName(roleName);
            int k = roleDao.addRole(role);
            //新增中间表
            middleDao.addMiddle(k,ids);
            k1 = 1;
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } finally {

        }

        return k1;
    }

    @Override
    public Role findById(int roleId) {
        Role role = roleDao.findById(roleId);
        List<Menu> menuList = role.getMenuList();//未分级
        List<Menu> newMenuList = new ArrayList<>();//分级后
        for ( Menu m : menuList) {
            if(m.getUpmenuId()==0) {//1级菜单
                List<Menu> secondList = new ArrayList<>();
                for(Menu m2 : menuList) {
                    if(m2.getUpmenuId()==m.getMenuId()) {
                        secondList.add(m2);
                    }
                }
                m.setSecondMenuList(secondList);
                newMenuList.add(m);
            }

        }
        role.setMenuList(newMenuList);
        return role;
    }

    @Override
    public int updateRole(Role role,String[] menuIds) {
        int k = 0;
        try {
            int i = roleDao.updateRole(role);
            //删除中间表
            middleDao.delMiddle(role.getRoleId());
            //添加中间表
            middleDao.addMiddle(role.getRoleId(),menuIds);
            k = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return k;
    }

    @Override
    public int deleteRole(int roleId) {
        int k = 0;
        try {
            //删除中间表
            middleDao.delMiddle(roleId);
            //删除角色
            roleDao.deleteRole(roleId);
            k = 1;
        }catch (Exception e) {
            e.printStackTrace();
        }
        return k;
    }

    @Override
    public int startRole(int roleId) {
        return roleDao.startRole(roleId);
    }
}
